<?php
/**
 * Controller for the Category-Model
 *
 * PHP versions 4 and 5
 *
 * TutoriumBase (http://tutoriumbase.my-reality.de)
 * Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 *
 *
 * @copyright     Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 * @link          http://tutoriumbase.my-reality.de TutoriumBase
 * @since         TutoriumBase v 0.1
 */

class CategoriesController extends AppController {
    
    var $name = 'Categories';
    
    
    /**
     * Show all tutorials of the current category-id
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.0
     */
    function view($id) {
        $selected_categories = $this->Category->CategoryCount->findAllByCategoryId($id);   
        $tutorials = array();
        
        if (empty($selected_categories)) {
            // Don't exists -> redirect to front page
            $this->redirect(array('controller' => 'tutorials', 'action' => 'index'));
        }
        
        // Load tutorial arrays into data
        foreach ($selected_categories as $category) {
            $tutorials[$category['Tutorial']['id']] = 
            $this->Category->CategoryCount->Tutorial->findById($category['Tutorial']['id']);
            
            // Sort tutorials by inner order
            $tutorials[$category['Tutorial']['id']]['Chapter'] 
                            = Set::sort($tutorials[$category['Tutorial']['id']]['Chapter'], '{n}.inner_order', 'asc');
        }
        
        // Searching for categories
        foreach ($tutorials as &$tutorial) {
            foreach ($tutorial['CategoryCount'] as $catcount) {
                $tutorial['Category'][] = $this->Category->findById($catcount['category_id']);
            }
        }        
        
        // Set data
        $this->set('tutorials', $tutorials);
        $this->Category->id = $id;
        $category = $this->Category->read();
        $this->setPageTitle('Kategorie: ' . $category['Category']['name']);  
    }
}
?>
